<template>
  <el-dialog
    v-model="dialogVisible"
    title="确认场景图"
    width="80%"
    :before-close="handleClose"
    :close-on-click-modal="false"
    class="pre-generate-dialog"
    style="width: 80% !important;"
  >
    <div class="image-list-container">
      <!-- 正在生成的提示 -->
      <div v-if="hasGeneratingImage" class="image-item loading-item">
        <div class="loading-content">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span>生成中...</span>
        </div>
      </div>
      
      <!-- 图片列表 -->
      <div 
        v-for="(image, index) in imageList" 
        :key="index" 
        class="image-item"
        :class="{ 'selected-image': index === selectedImageIndex }"
        @mouseenter="handleMouseEnter(index)"
        @mouseleave="handleMouseLeave"
        @click="selectImage(index)"
      >
        <img :src="image.url" :alt="`生成图片 ${index + 1}`" class="preview-image" />
        
        <!-- 选中标记 -->
        <div v-if="index === selectedImageIndex" class="selected-indicator">
          <el-icon class="check-icon"><Check /></el-icon>
        </div>
        
        
        <!-- 图片操作菜单 -->
        <div class="image-actions">
          <div class="opt-wrapper" @click.stop="handleAction('enhance', image)" v-if="image?.businessSupport !== 'seed'">
            <svg-icon class="opt-icon" icon-class="zengqiang" />
            <div class="opt-text">增强</div>
          </div>
          <div class="opt-wrapper" @click.stop="handleAction('refine', image)" v-if="image?.businessSupport !== 'seed'">
            <svg-icon class="opt-icon" icon-class="jingxi" />
            <div class="opt-text">精细</div>
          </div>
          <div class="opt-wrapper" @click.stop="handleImageEdit(image)">
            <svg-icon class="opt-icon" icon-class="zhonghui" />
            <div class="opt-text">编辑</div>
          </div>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button color="#1c1d29" @click="handleConfirm" :disabled="imageList.length === 0">
          确定
        </el-button>
      </span>
    </template>

    <!-- 图片预览 -->
    <div v-if="previewVisible" class="image-preview-overlay" @click="previewVisible = false">
      <div class="image-preview-container">
        <img :src="previewImageUrl" class="preview-image-big" />
        <div class="close-button" @click.stop="previewVisible = false">
          <el-icon><Close /></el-icon>
        </div>
      </div>
    </div>
  </el-dialog>

  <!-- 图片编辑弹窗 -->
  <ImageEditorModal
    v-model:visible="imageEditorVisible"
    :image-url="editingImageUrl"
    :business-id="editingBusinessId"
    :business-type="editingBusinessType"
    @close="handleImageEditorClose"
    @save="handleImageEditorSave"
    @generation-completed="handleImageGenerationCompleted"
  />
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading, Check, Close } from '@element-plus/icons-vue'
import { 
  generateImages, 
  enhanceImage, 
  refineImage, 
  redrawImage, 
  getGeneratingStatus,
  getImageList
} from '@/api/imageGeneration'
import request from '@/utils/request'
import ImageEditorModal from '@/components/common/ImageEditorModal.vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  sceneId: {
    type: String,
    default: ''
  },
  initialDescription: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:visible', 'confirm', 'cancel'])

const previewVisible = ref(false)
const previewImageUrl = ref('')

const previewImage = (url) => {
  previewImageUrl.value = url
  previewVisible.value = true
}

// 弹窗显示状态
const dialogVisible = ref(props.visible)

// 监听visible属性变化
watch(() => [props.visible, props.sceneId], (newVal) => {
  console.log('newVal', newVal)
  dialogVisible.value = newVal[0]
  if (newVal[0] && newVal[1]) {
    fetchImageList()
  }
})

// 监听dialogVisible变化，同步回父组件
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 描述文本
const description = ref(props.initialDescription)

// 图片列表
const imageList = ref([])

// 悬浮状态
const hoveredIndex = ref(null)

// 选中的图片索引
const selectedImageIndex = ref(0)

// 是否有正在生成的图片
const hasGeneratingImage = ref(false)

// 是否正在生成
const isGenerating = ref(false)

// 定时器ID
let checkStatusTimer = null

// 鼠标悬浮处理
const handleMouseEnter = (index) => {
  hoveredIndex.value = index
}

const handleMouseLeave = () => {
  hoveredIndex.value = null
}

const fetchImageInterval = ref(null)

// 图片编辑弹窗相关
const imageEditorVisible = ref(false)
const editingImageUrl = ref('')
const editingBusinessType = ref('SCENE')
const editingBusinessId = ref('')

// 获取图片列表
const fetchImageList = async () => {
  try {
    // 调用API获取图片列表
    const res = await getImageList({ sceneId: props.sceneId })
    console.log('res', res)
    if (res.data && res.data.imageProcessVO.processing) {
      hasGeneratingImage.value = true
      if(!fetchImageInterval.value) {
        fetchImageInterval.value = setInterval(fetchImageList, 15000)
      }
    }
    if (res.data && !res.data.imageProcessVO.processing) {
      hasGeneratingImage.value = false
      if(fetchImageInterval.value) {
        clearInterval(fetchImageInterval.value)
        fetchImageInterval.value = null
      }
    }
    if (res.data && res.data.imageProcessVO.imageTaskList) {
      imageList.value = res.data.imageProcessVO.imageTaskList
      // 默认选中第一张图片
      if (imageList.value.length > 0) {
        selectedImageIndex.value = 0
      }
    }
  } catch (error) {
    hasGeneratingImage.value = false
    if(fetchImageInterval.value) {
      clearInterval(fetchImageInterval.value)
      fetchImageInterval.value = null
    }
    console.error('获取图片列表失败:', error)
  }
}

// 处理操作按钮点击
const handleAction = async (actionType, image) => {
  const actionNames = {
    enhance: '增强',
    refine: '精细',
    redraw: '重绘'
  }
  const actionMap = {
    enhance: 'VARY_HIGH',
    refine: 'VARY_LOW',
    redraw: 'REROLL'
  }
  try {
    hasGeneratingImage.value = true
    await request({
      url: '/evox-drama/image/change?taskAction=' + actionMap[actionType] + '&taskId=' + image.taskId,
      method: 'post'
    })
    // 可选：刷新图片列表
    fetchImageList()
  } catch (error) {
    console.error(`${actionNames[actionType]}失败:`, error)
    ElMessage.error(`${actionNames[actionType]}失败`)
    setTimeout(() => {
      hasGeneratingImage.value = false
    }, 1000)
  }
}

// 打开图片编辑弹窗
const handleImageEdit = (image) => {
  if (!image || !image.url) return
  editingImageUrl.value = image.url
  editingBusinessType.value = image.businessType || 'SCENE'
  editingBusinessId.value = props.sceneId
  imageEditorVisible.value = true
  // 临时隐藏当前弹窗，不触发重置逻辑
  dialogVisible.value = false
  emit('update:visible', false)
}

// 关闭图片编辑弹窗
const handleImageEditorClose = () => {
  imageEditorVisible.value = false
  editingImageUrl.value = ''
  editingBusinessType.value = 'SCENE'
  editingBusinessId.value = ''
  // 关闭编辑器后恢复场景确认弹窗
  dialogVisible.value = true
  emit('update:visible', true)
}

// 图片编辑保存回调
const handleImageEditorSave = async (saveData) => {
  // 仅刷新列表，实际确认逻辑由上游业务决定
  try {
    await fetchImageList()
    ElMessage.success('图片保存成功')
  } catch (e) {
    // ignore
  } finally {
    // 关闭编辑器并恢复场景弹窗
    imageEditorVisible.value = false
    editingImageUrl.value = ''
    editingBusinessType.value = 'SCENE'
    editingBusinessId.value = ''
    dialogVisible.value = true
    emit('update:visible', true)
  }
}

// 图片编辑内部生成完成（如增强/精细等）后刷新本弹窗的图片列表
const handleImageGenerationCompleted = async () => {
  await fetchImageList()
}

// 选择图片
const selectImage = (index) => {
  if (selectedImageIndex.value === index) {
    previewImage(imageList.value[index].url)
    return
  }
  selectedImageIndex.value = index
}

// 确认选择
const handleConfirm = () => {
  if (imageList.value.length === 0) {
    ElMessage.warning('请先生成图片')
    return
  }
  
  // 返回选中图片的URL
  if(fetchImageInterval.value) {
    clearInterval(fetchImageInterval.value)
    fetchImageInterval.value = null
  }
  emit('confirm', imageList.value[selectedImageIndex.value].url)
  hasGeneratingImage.value = false
  imageList.value = []
  dialogVisible.value = false
}

// 取消选择
const handleCancel = () => {
  emit('cancel')
  if(fetchImageInterval.value) {
    clearInterval(fetchImageInterval.value)
    fetchImageInterval.value = null
  }
  hasGeneratingImage.value = false
  imageList.value = []
  dialogVisible.value = false
}

// 关闭弹窗
const handleClose = () => {
  if(fetchImageInterval.value) {
    clearInterval(fetchImageInterval.value)
    fetchImageInterval.value = null
  }
  hasGeneratingImage.value = false
  imageList.value = []
  dialogVisible.value = false
}

// 组件挂载时
onMounted(() => {
  // 初始化时获取图片列表
  if (props.visible) {
    fetchImageList()
  }
  
  // 启动定时检查
  // checkStatusTimer = setInterval(checkGeneratingStatus, 5000)
})

// 组件卸载时
onUnmounted(() => {
  // 清除定时器
  if (fetchImageInterval.value) {
    clearInterval(fetchImageInterval.value)
    fetchImageInterval.value = null
  }
})
</script>

<style scoped>
.pre-generate-dialog :deep(.el-dialog__body) {
  padding-top: 10px;
  width: 80% !important;
}

.description-area {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.description-area .el-textarea {
  flex: 1;
}

.image-list-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}
.blank{
  width: 100%;
  height: 16px;
}

.image-item {
  width: calc(20% - 12px);
  position: relative;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
}

.selected-image {
  border: 2px solid #3644E0;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.15);
}

.selected-indicator {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 24px;
  height: 24px;
  background-color: #3644E0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.check-icon {
  font-size: 16px;
}

@media screen and (max-width: 1400px) {
  .image-item {
    width: calc(25% - 12px);
  }
}

@media screen and (max-width: 1100px) {
  .image-item {
    width: calc(33.33% - 10px);
  }
}

@media screen and (max-width: 768px) {
  .image-item {
    width: calc(50% - 8px);
  }
}

.preview-image {
  width: 100%;
  aspect-ratio: 9 / 16;
  object-fit: cover;
  display: block;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  transition: opacity 0.3s;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.loading-item {
  background: linear-gradient(205.92deg, #C0CEFF 1.74%, #CDF2FF 52.4%, #F8CEFF 105.69%);
  background-size: 200% 200%;
  animation: gradientMove 4s ease infinite;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

@keyframes gradientMove {
  0% {
    background-position: 0% 100%;
  }
  50% {
    background-position: 100% 0%;
  }
  100% {
    background-position: 0% 100%;
  }
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  color: #fff;
  text-shadow: 0px 1px 2px rgba(0, 0, 0, 0.1);
  font-weight: 500;
}

.loading-icon {
  font-size: 30px;
  animation: rotate 1.5s linear infinite;
}
.image-actions {
  display: flex;
  justify-content: space-around;
  padding: 8px;
  background-color: #f5f7fa;
  border-top: 1px solid #e4e7ed;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 图片预览样式 */
.image-preview-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.image-preview-container {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-image-big {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
}

.close-button {
  position: absolute;
  top: -40px;
  right: -40px;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: white;
  font-size: 20px;
  transition: background-color 0.3s;
}

.close-button:hover {
  background-color: rgba(255, 255, 255, 0.4);
}
.opt-wrapper {
  flex: 1;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  border-radius: 4px;
}
.opt-wrapper:hover {
  background: rgba(162, 166, 184, 0.1);
}
.opt-icon {
  font-size: 12px;
}
.opt-text {
  color: #1C1D29;
  font-size: 12px;
}
</style> 